package com.example.administrator.hqq.activity.register;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.v7.app.AlertDialog;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;

import com.blankj.utilcode.util.SPUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.example.administrator.hqq.MainActivity;
import com.example.administrator.hqq.R;

import com.example.administrator.hqq.activity.LogInActivity;

import com.example.administrator.hqq.base.MyActivity;
import com.example.administrator.hqq.base.MyApplication;
import com.example.administrator.hqq.bean.RegisterBeen;

import com.example.administrator.hqq.config.LoongsConfig;
import com.example.administrator.hqq.config.UrlFactory;
import com.example.administrator.hqq.utils.GetLocationUtils;
import com.example.administrator.hqq.utils.HintWordsUtils;
import com.google.gson.Gson;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import okhttp3.Call;
import permissions.dispatcher.NeedsPermission;
import permissions.dispatcher.OnNeverAskAgain;
import permissions.dispatcher.OnPermissionDenied;
import permissions.dispatcher.OnShowRationale;
import permissions.dispatcher.PermissionRequest;
import permissions.dispatcher.RuntimePermissions;

/**
 * @author 康海涛
 * 开机大图
 */
@RuntimePermissions
public class LoadingFigureActivity extends MyActivity {
    private Handler handler=new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message message) {
            //当what==3时候表示第一次打开app
            if (message.what==LoongsConfig.three_seconds)
            {
                Intent intent = new Intent(LoadingFigureActivity.this, LogInActivity.class);
                startActivity(intent);
                finish();
            }
            else{
                String loginToken = SPUtils.getInstance().getString( LoongsConfig.loginToken, "");
                String userID = SPUtils.getInstance().getString( LoongsConfig.user_id, "");
                //当userID不为空时候做自动登录
                if (!TextUtils.isEmpty(loginToken)&&!TextUtils.isEmpty(userID))
                {
                    userLogin(loginToken,userID);
                }
                else{
                    Intent intent = new Intent(LoadingFigureActivity.this, LogInActivity.class);
                    startActivity(intent);
                    finish();
                }
            }
            return false;
        }
    });
    private String TAG=this.getClass().getSimpleName();
    private int i=0;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_loading_figure);
        LoadingFigureActivityPermissionsDispatcher.startLocationWithCheck(LoadingFigureActivity.this);
//        handler.sendEmptyMessageDelayed(LoongsConfig.three_seconds,5000);
//        initdata();
//        initview();
    }

    private void initdata() {

        if (!SPUtils.getInstance().getBoolean(LoongsConfig.guide,false))
        {
            handler.sendEmptyMessageDelayed(LoongsConfig.three_seconds,1000);
        }
        else{
            handler.sendEmptyMessageDelayed(1,1000);
        }
    }

    private void userLogin(String loginToken, final String userID) {
        OkHttpUtils.get().url(UrlFactory.login())
                .addParams(LoongsConfig.user_id,userID)
                .addParams(LoongsConfig.token,loginToken)
                .build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e,int id) {
                Log.e(TAG, "自动登录onError: "+e.getMessage() );
                ToastUtils.showShort("自动登录验证失败请从新登录");
                Intent intent = new Intent(LoadingFigureActivity.this, LogInActivity.class);
                startActivity(intent);
                finish();
            }
            @Override
            public void onResponse(String s,int id) {
                Log.e(TAG, "自动登录onResponse: "+s );
                Gson gson = new Gson();
                RegisterBeen registerBeen = gson.fromJson(s, RegisterBeen.class);
                //当code==200时候表示自动登录成功
                HintWordsUtils.showMarkeWords(registerBeen.getCode(),registerBeen.getDescription());
                if (registerBeen.getCode()==200)
                {
                    String login_token = registerBeen.getLogin_token();
                    String rongToken = registerBeen.getRongyun_token();
                    String gender = registerBeen.getGender();
                    SPUtils.getInstance().put(LoongsConfig.gender,gender);
                    MyApplication.setUMAlias(userID);
                    Log.e(TAG, "自动登录: "+"login_token:"+login_token+"rongToken:"+rongToken);
                    SPUtils.getInstance().put(LoongsConfig.loginToken,login_token);
                    SPUtils.getInstance().put(LoongsConfig.rongToken,rongToken);
                    Intent intent = new Intent(LoadingFigureActivity.this, MainActivity.class);
                    startActivity(intent);
                    finish();
                }
                //表示登录过期需要从新验证手机短信
                else{
                    Intent intent = new Intent(LoadingFigureActivity.this, LogInActivity.class);
                    startActivity(intent);
                    finish();
                }
            }
        });
    }

    /**
     * 申请权限
     */
    @SuppressLint("NoCorrespondingNeedsPermission")
    @OnShowRationale({Manifest.permission.ACCESS_FINE_LOCATION,Manifest.permission.ACCESS_COARSE_LOCATION
            ,Manifest.permission.WRITE_EXTERNAL_STORAGE
            ,Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.READ_PHONE_STATE})
    void showRationaleForLocation(final PermissionRequest request) {
        new AlertDialog.Builder(this)
                .setMessage("我们将会获取下面一些权限")
                .setPositiveButton("同意", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        request.proceed();
                    }
                })
                .setNegativeButton("拒绝", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        request.cancel();
                    }
                })
                .show();
    }

    @OnPermissionDenied({Manifest.permission.ACCESS_FINE_LOCATION,Manifest.permission.ACCESS_COARSE_LOCATION
            ,Manifest.permission.WRITE_EXTERNAL_STORAGE
            ,Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.READ_PHONE_STATE})
    void showDeniedForLocation() {
        Toast.makeText(this, getString(R.string.permission_denied), Toast.LENGTH_SHORT).show();
    }

    @OnNeverAskAgain({Manifest.permission.ACCESS_FINE_LOCATION,Manifest.permission.ACCESS_COARSE_LOCATION
            ,Manifest.permission.WRITE_EXTERNAL_STORAGE
            ,Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.READ_PHONE_STATE})
    void showNeverAskForLocation() {
        Toast.makeText(this, getString(R.string.permission_never_ask), Toast.LENGTH_SHORT).show();
    }

    @NeedsPermission({Manifest.permission.ACCESS_FINE_LOCATION,Manifest.permission.ACCESS_COARSE_LOCATION
            ,Manifest.permission.WRITE_EXTERNAL_STORAGE
            ,Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.READ_PHONE_STATE})
    public void startLocation() {
        //授权成功
        GetLocationUtils.getloction(LoadingFigureActivity.this.getApplicationContext());
        initdata();
    }
    @SuppressLint("NeedOnRequestPermissionsResult")
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        LoadingFigureActivityPermissionsDispatcher.onRequestPermissionsResult(this, requestCode, grantResults);
    }

    @Override
    protected String getActivityName() {
        return this.getClass().getSimpleName();
    }
}
